package com.njupt.LinkTable;

/**
 * @Author: wujiaming
 * @CreateTime: 2025/2/18 9:39
 * @Description: 160. 相交链表
 * @Version: 1.0
 */


public class GetIntersectionNode_160 {



    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode curA = headA;
        ListNode curB = headB;

        int lenA = 0;
        int lenB = 0;

        while(curA != null){
            lenA++;
            curA = curA.next;
        }
        curA = headA;

        while(curB != null){
            lenB++;
            curB = curB.next;
        }
        curB = headB;

        if(lenB < lenA){
            int t = lenB;
            lenB = lenA;
            lenA = t;

            ListNode temp = curB;
            curB = curA;
            curA = temp;
        }
         int gap = lenB - lenA;
        while(gap !=0){
            curB = curB.next;
            gap--;
        }

        while(curA != null && curB != null){
            if(curA == curB){
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return null;
    }


    public static void main(String[] args) {
        ListNode headA = new ListNode(4);
        ListNode node1 = new ListNode(1);
        ListNode node8 = new ListNode(8);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        headA.next = node1;node1.next = node8;node8.next=node4;node4.next=node5;


        ListNode headB = new ListNode(5);
        ListNode node6 = new ListNode(6);
        headB.next = node6; node6.next = node1;node1.next = node8;node8.next=node4;node4.next=node5;


        GetIntersectionNode_160 test = new GetIntersectionNode_160();
        ListNode node = test.getIntersectionNode(headA, headB);
        System.out.println(node.val);

    }
}
